<script setup lang="ts">
import type { VbenFormProps } from '@vben/common-ui';

import type { VxeGridProps } from '#/adapter/vxe-table';
import type { Post } from '#/api/system/post/model';
import type { DictOption } from '#/store/dict';

import { onMounted, ref } from 'vue';

import { Page, useVbenDrawer } from '@vben/common-ui';
import { DictEnum } from '@vben/constants';
import { $t } from '@vben/locales';

import { ElMessageBox } from 'element-plus';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { deletePost, exportPost, getPostList } from '#/api/system/post/post';
import { DictTag } from '#/components/dict/index';
import { getDictOptions } from '#/utils/dict';
import { commonDownloadExcel } from '#/utils/file/download';

import { querySchema, tableColumns } from './config-data';
import PostDrawer from './post-drawer.vue';

const [PostVbenDrawer, postVbenDrawerApi] = useVbenDrawer({
  connectedComponent: PostDrawer,
});

const formOptions: VbenFormProps = {
  schema: querySchema(),
  wrapperClass: 'grid-cols-4',
};

const gridOptions: VxeGridProps = {
  checkboxConfig: {
    // 高亮
    highlight: true,
    // 翻页时保留选中状态
    reserve: true,
  },
  columns: tableColumns,
  size: 'medium',
  height: 'auto',
  // 配置表格右上角全屏、刷新
  toolbarConfig: {
    custom: true,
    refresh: true,
    zoom: true,
  },
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        const resp = await getPostList({
          ...formValues,
          pageNum: page.currentPage,
          pageSize: page.pageSize,
        });
        return { items: resp.rows, total: resp.total };
      },
    },
  },
};
const [BasicTable, basicTableApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
});
// 添加岗位
function addPost() {
  postVbenDrawerApi.setData({ isUpdate: false }).open();
}
// 批量删除岗位
async function removePost() {
  const checkData = basicTableApi.grid.getCheckboxRecords();
  const postIds = checkData.map((item: Post) => item.postId);
  ElMessageBox.confirm(`确认删除选中的${postIds.length}条数据吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    await deletePost(postIds);
    await basicTableApi.reload();
  });
}
// 单个删除岗位
async function confirmEvent(post: Post) {
  const postIds = [];
  postIds.push(post.postId);
  await deletePost(postIds);
  await basicTableApi.reload();
}
// 编辑岗位
function handleEdit(post: Post) {
  postVbenDrawerApi.setData({ postId: post.postId, isUpdate: true }).open();
}
// 导出角色
async function exportPostData() {
  await commonDownloadExcel(
    exportPost,
    '岗位数据',
    basicTableApi.formApi.form.values,
  );
}
// 获取状态字典值
const dictRef = ref<DictOption[]>([]);
onMounted(async () => {
  dictRef.value = await getDictOptions(DictEnum.SYS_NORMAL_DISABLE);
});
</script>

<template>
  <Page :auto-content-height="true">
    <BasicTable table-title="岗位列表">
      <template #toolbar-tools>
        <ElSpace>
          <ElButton
            @click="exportPostData"
            v-access:code="['system:post:export']"
          >
            导出
          </ElButton>
          <ElButton
            type="danger"
            :disabled="
              !(basicTableApi?.grid?.getCheckboxRecords?.()?.length > 0)
            "
            @click="removePost"
            v-access:code="['system:post:remove']"
          >
            删除
          </ElButton>
          <ElButton
            type="primary"
            @click="addPost"
            v-access:code="['system:post:add']"
          >
            新增
          </ElButton>
        </ElSpace>
      </template>
      <template #status="{ row }">
        <DictTag :dicts="dictRef" :value="row.status" />
      </template>
      <template #action="{ row }">
        <ElSpace>
          <ElButton
            size="small"
            type="primary"
            plain
            @click="handleEdit(row)"
            v-access:code="['system:post:edit']"
          >
            编辑
          </ElButton>
          <ElPopconfirm
            :title="$t('common.confirm-delete')"
            @confirm="confirmEvent(row)"
          >
            <template #reference>
              <ElButton
                size="small"
                type="danger"
                plain
                v-access:code="['system:post:remove']"
              >
                删除
              </ElButton>
            </template>
          </ElPopconfirm>
        </ElSpace>
      </template>
    </BasicTable>
    <PostVbenDrawer @reload="basicTableApi.reload()" />
  </Page>
</template>
